"""文本检测服务主类"""

from typing import Optional, Dict, Any, List
from datetime import datetime

from app.core.config import settings
from app.models.enums import DetectionPlatform, DetectionStatus
from app.models.request import TextDetectionRequest, BatchDetectionRequest
from app.models.response import TextDetectionResponse, BatchDetectionResponse
from app.utils.logger import get_logger
from app.utils.exceptions import PlatformNotSupportedException, TaskNotFoundException
from app.utils.validators import TextValidator

from .platforms.zhiwang import ZhiwangDetectionPlatform
from .platforms.gezida import GezidaDetectionPlatform
from .platforms.weipu import WeipuDetectionPlatform

logger = get_logger("text_detection_service")


class TextDetectionService:
    """文本检测服务主类"""
    
    def __init__(self):
        self.platforms = self._initialize_platforms()
        self.validator = TextValidator()
        self.task_cache: Dict[str, TextDetectionResponse] = {}
    
    def _initialize_platforms(self) -> Dict[DetectionPlatform, Any]:
        """初始化检测平台"""
        platforms = {}
        
        try:
            # 初始化知网平台
            if settings.zhiwang_api_url and settings.zhiwang_api_key:
                platforms[DetectionPlatform.ZHIWANG] = ZhiwangDetectionPlatform(
                    settings.zhiwang_api_url,
                    settings.zhiwang_api_key
                )
                logger.info("知网检测平台初始化成功")
            
            # 初始化格子达平台
            if settings.gezida_api_url and settings.gezida_api_key:
                platforms[DetectionPlatform.GEZIDA] = GezidaDetectionPlatform(
                    settings.gezida_api_url,
                    settings.gezida_api_key
                )
                logger.info("格子达检测平台初始化成功")
            
            # 初始化维普平台
            if settings.weipu_api_url and settings.weipu_api_key:
                platforms[DetectionPlatform.WEIPU] = WeipuDetectionPlatform(
                    settings.weipu_api_url,
                    settings.weipu_api_key
                )
                logger.info("维普检测平台初始化成功")
            
        except Exception as e:
            logger.error(f"平台初始化失败: {e}")
        
        return platforms
    
    def get_available_platforms(self) -> List[Dict[str, Any]]:
        """获取可用的检测平台列表"""
        platforms_info = []
        
        for platform_enum, platform_instance in self.platforms.items():
            try:
                info = platform_instance.get_platform_info()
                platforms_info.append(info)
            except Exception as e:
                logger.error(f"获取平台 {platform_enum.value} 信息失败: {e}")
        
        return platforms_info
    
    def _get_platform_instance(self, platform: DetectionPlatform):
        """获取平台实例"""
        if platform not in self.platforms:
            raise PlatformNotSupportedException(platform.value)
        
        return self.platforms[platform]
    
    async def submit_detection(self, request: TextDetectionRequest) -> TextDetectionResponse:
        """提交文本检测任务"""
        try:
            logger.info(f"提交文本检测任务，平台: {request.platform.value}")
            
            # 验证文本
            is_valid, clean_text, error_msg = self.validator.sanitize_and_validate(request.text)
            if not is_valid:
                raise ValueError(f"文本验证失败: {error_msg}")
            
            # 获取平台实例
            platform = self._get_platform_instance(request.platform)
            
            # 提交检测任务
            result = await platform.submit_detection(
                text=clean_text,
                title=request.title,
                author=request.author
            )
            
            # 缓存结果
            self.task_cache[result.task_id] = result
            
            logger.info(f"检测任务提交成功: {result.task_id}")
            return result
            
        except PlatformNotSupportedException:
            raise
        except Exception as e:
            logger.error(f"提交检测任务失败: {e}")
            raise
    
    async def get_detection_result(self, task_id: str) -> TextDetectionResponse:
        """获取检测结果"""
        try:
            logger.info(f"获取检测结果: {task_id}")
            
            # 首先检查缓存
            if task_id in self.task_cache:
                cached_result = self.task_cache[task_id]
                
                # 如果状态不是最终状态，尝试更新
                if cached_result.status not in [DetectionStatus.COMPLETED, DetectionStatus.FAILED]:
                    platform = self._get_platform_instance(cached_result.platform)
                    updated_result = await platform.get_detection_result(task_id)
                    self.task_cache[task_id] = updated_result
                    return updated_result
                
                return cached_result
            
            # 如果缓存中没有，尝试从所有平台查询
            for platform_instance in self.platforms.values():
                try:
                    result = await platform_instance.get_detection_result(task_id)
                    self.task_cache[task_id] = result
                    return result
                except Exception:
                    continue
            
            raise TaskNotFoundException(task_id)
            
        except TaskNotFoundException:
            raise
        except Exception as e:
            logger.error(f"获取检测结果失败: {e}")
            raise
    
    async def cancel_detection(self, task_id: str) -> bool:
        """取消检测任务"""
        try:
            logger.info(f"取消检测任务: {task_id}")
            
            # 检查缓存中的任务信息
            if task_id not in self.task_cache:
                raise TaskNotFoundException(task_id)
            
            cached_result = self.task_cache[task_id]
            platform = self._get_platform_instance(cached_result.platform)
            
            success = await platform.cancel_detection(task_id)
            
            if success:
                # 更新缓存中的状态
                cached_result.status = DetectionStatus.CANCELLED
                cached_result.updated_at = datetime.now()
                self.task_cache[task_id] = cached_result
            
            return success
            
        except TaskNotFoundException:
            raise
        except Exception as e:
            logger.error(f"取消检测任务失败: {e}")
            return False
    
    async def submit_batch_detection(self, request: BatchDetectionRequest) -> BatchDetectionResponse:
        """提交批量检测任务"""
        try:
            logger.info(f"提交批量检测任务，任务数量: {len(request.texts)}")
            
            batch_id = f"batch_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            tasks = []
            completed_count = 0
            failed_count = 0
            
            for i, text_request in enumerate(request.texts):
                try:
                    result = await self.submit_detection(text_request)
                    tasks.append(result)
                    if result.status == DetectionStatus.COMPLETED:
                        completed_count += 1
                    elif result.status == DetectionStatus.FAILED:
                        failed_count += 1
                except Exception as e:
                    logger.error(f"批量任务中第 {i+1} 个任务提交失败: {e}")
                    failed_count += 1
            
            return BatchDetectionResponse(
                batch_id=batch_id,
                total_count=len(request.texts),
                completed_count=completed_count,
                failed_count=failed_count,
                tasks=tasks
            )
            
        except Exception as e:
            logger.error(f"提交批量检测任务失败: {e}")
            raise
    
    async def get_detection_history(self, page: int = 1, size: int = 10, 
                                  platform: Optional[DetectionPlatform] = None) -> List[TextDetectionResponse]:
        """获取检测历史"""
        try:
            logger.info(f"获取检测历史，页码: {page}, 大小: {size}")
            
            # 从缓存中获取历史记录
            all_tasks = list(self.task_cache.values())
            
            # 按平台筛选
            if platform:
                all_tasks = [task for task in all_tasks if task.platform == platform]
            
            # 按创建时间倒序排序
            all_tasks.sort(key=lambda x: x.created_at, reverse=True)
            
            # 分页
            start_index = (page - 1) * size
            end_index = start_index + size
            
            return all_tasks[start_index:end_index]
            
        except Exception as e:
            logger.error(f"获取检测历史失败: {e}")
            return []
    
    def get_platform_statistics(self) -> Dict[str, Any]:
        """获取平台统计信息"""
        try:
            stats = {
                "total_platforms": len(self.platforms),
                "available_platforms": 0,
                "total_tasks": len(self.task_cache),
                "platform_details": []
            }
            
            for platform_enum, platform_instance in self.platforms.items():
                try:
                    is_available = platform_instance.validate_api_connection()
                    if is_available:
                        stats["available_platforms"] += 1
                    
                    platform_tasks = [
                        task for task in self.task_cache.values() 
                        if task.platform == platform_enum
                    ]
                    
                    stats["platform_details"].append({
                        "platform": platform_enum.value,
                        "is_available": is_available,
                        "task_count": len(platform_tasks),
                        "features": platform_instance._get_platform_features()
                    })
                    
                except Exception as e:
                    logger.error(f"获取平台 {platform_enum.value} 统计失败: {e}")
            
            return stats
            
        except Exception as e:
            logger.error(f"获取平台统计失败: {e}")
            return {}
    
    def clear_cache(self, older_than_hours: int = 24):
        """清理缓存"""
        try:
            current_time = datetime.now()
            expired_tasks = []
            
            for task_id, task in self.task_cache.items():
                time_diff = current_time - task.created_at
                if time_diff.total_seconds() > older_than_hours * 3600:
                    expired_tasks.append(task_id)
            
            for task_id in expired_tasks:
                del self.task_cache[task_id]
            
            logger.info(f"清理了 {len(expired_tasks)} 个过期任务缓存")
            
        except Exception as e:
            logger.error(f"清理缓存失败: {e}") 